package com.tianyi.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.tianyi.comUser.ComUserService;
import com.tianyi.dao.entity.comUser.ComUser;
import com.tianyi.dao.entity.userRegion.UserRegion;
import com.tianyi.lib.bo.wechat.AuthJsToken;
import com.tianyi.lib.model.WebResult;
import com.tianyi.lib.req.BaseReq;
import com.tianyi.lib.req.UserAddrReq;
import com.tianyi.lib.req.UserAuditInfoReq;
import com.tianyi.userRegion.UserRegionService;
import com.tianyi.vo.comUser.ComUserDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.weixin4j.WeixinException;
import org.weixin4j.WeixinSupport;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.Response;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * wechat service
 *
 * @author cuixuhui
 * @date 2020/05/07
 */
@Service
public class WeChatService extends WeixinSupport {

    private static final Logger logger = LoggerFactory.getLogger(WeChatService.class);
    /**
     * 微信小程序appid
     */
    private static final String appid = "wxa72888c497ae8cef";
    /**
     * 微信小程序密钥
     */
    private static final String secret = "71fb1c8e692aed6110facbea4e88fbcb";
    private static final String grant_type = "authorization_code";

    @Autowired
    private ComUserService comUserService;
    @Autowired
    private UserRegionService userRegionService;



    /**
     * 根据code获取构建发微信api的参数
     * @param code
     * @return
     */
    public String getWeChartOpenIdParam(String code){

        StringBuilder builder = new StringBuilder();
        builder.append("?grant_type=").append(grant_type)
                .append("&appid=" ).append(appid)
                .append("&secret=").append(secret)
                .append("&js_code=").append(code);
        return builder.toString();
    }

    public Map<String, Object> login(String code) {
        Map<String, Object> result = new HashMap<>(2);
        //拼接参数
        String param = getWeChartOpenIdParam(code);
        //创建请求对象
        HttpsClient http = new HttpsClient();
        Response res =null;
        try{
            //调用获取access_token接口
            res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
            //根据请求结果判定，是否验证成功
            JSONObject jsonObj = res.asJSONObject();
            if (Objects.isNull(jsonObj)) {

                return result;
            }
            Object errcode = jsonObj.get("errcode");
            if (Objects.nonNull(errcode)) {
                //返回异常信息
                throw new WeixinException(getCause(Integer.parseInt(errcode.toString())));
            }
            AuthJsToken authJsToken = JSON.parseObject(jsonObj.toJSONString(), AuthJsToken.class);
            logger.info("openid={} and session_key={}", authJsToken.getOpenid(), authJsToken.getSession_key());
            result.put("openid", authJsToken.getOpenid());
            result.put("session_key", authJsToken.getSession_key());

            //新增用户
            comUserService.insertComUser(authJsToken.getOpenid());
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public WebResult<ComUserDetailVO> getUserInfo(BaseReq req) {

        WebResult<ComUserDetailVO> comUserDetailVOWebResult = comUserService.queryComUserDetailById(req);
        return comUserDetailVOWebResult;
    }

    /**
     * 用户新增地址
     * @param req
     * @return
     */
    public WebResult<String> addAddress(UserAddrReq req) {

        return  userRegionService.addAddress(req);
    }

    /**
     * 用户修改地址
     * @param req
     * @return
     */
    public WebResult<String> updateAddress(UserAddrReq req) {
        return userRegionService.updateAddress(req);
    }

    /**
     * 获取用户地址列表  默认20条
     * @param req
     * @return
     */
    public WebResult<PageInfo<UserRegion>> queryUserAddressPage(UserAddrReq req) {

        return userRegionService.queryAddress(req);
    }

    public WebResult<String> uploadUserBuCardPhoto(UserAuditInfoReq req) {

        return comUserService.userUploadBuCardPhoto(req);
    }

    public WebResult<String> updateUserInfo(UserAuditInfoReq req) {

        return comUserService.submitUserAuditInfo(req);
    }
}
